<template>
  <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <h2>用户列表</h2>
        <!-- 卡片视图区域 -->
        <el-card class="box-card">
            <!-- 搜索与添加区域 -->
           
            <el-row :gutter=20>
                <el-col :span="7">  
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
                         <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input></el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="isShowDialog=true">添加用户</el-button>
                </el-col>
            </el-row>
                 <el-table
                :data="userList"
                style="width: 100%"
                border stripe>
                     <el-table-column
                        type ="index"
                        label="#"
                      >

                    </el-table-column>
                    <el-table-column
                        prop="username"
                        label="姓名"
                      >
                    </el-table-column>

                     <el-table-column
                        prop="email"
                        label="邮箱"
                       >
                    </el-table-column>

                    <el-table-column
                        prop="mobile"
                        label="电话"
                        >
                    </el-table-column>
                    
                    <el-table-column
                        prop="role_name"
                        label="角色"
                      >
                    </el-table-column>
                    
                    <el-table-column
                        prop="mg_state"
                        label="状态"
                    >
                      <template slot-scope="scope">
                              <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                      </template>
                        
                    </el-table-column>

                    <el-table-column
                        label="操作"
                        width="180px"
                      >
                      <template slot-scope="scope">
                        <!-- 修改按钮 -->
                          <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
                                 <el-button type="primary" icon="el-icon-edit" size='mini' @click="showEditDialog(scope.row.id)"></el-button>
                          </el-tooltip>
                         
                        <!-- 删除按钮 -->
                        
                          <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                               <el-button type="danger" icon="el-icon-delete" size='mini' @click="removeUserInfo(scope.row.id)"></el-button>
                          </el-tooltip>
                        <!-- 分配按钮 -->
                       
                          <el-tooltip class="item" effect="dark" content="分配" placement="top" :enterable="false">
                                <el-button type="warning" icon="el-icon-setting" size='mini' @click="showRolesDialog(scope.row)"></el-button>
                          </el-tooltip>
                      </template>
                    </el-table-column>
                </el-table>
                <!-- 分页区域 -->
                  <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="queryInfo.pagenum"
                  :page-sizes="[1, 2, 5, 10]"
                  :page-size="queryInfo.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">

                </el-pagination>
        </el-card>
      <!-- 添加用户时的对话框区域 -->
      <el-dialog
        title="添加用户"
        :visible.sync="isShowDialog"
        width="50%" @close="addUserFormClear()">
        <!-- 内容区 -->
        <el-form ref="addFormRef" :model="addUserForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
           <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
           <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
           <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowDialog = false">取 消</el-button>
          <el-button type="primary" @click="submit" >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改操作对话框 -->
       <el-dialog
        title="修改用户信息"
        :visible.sync="isShowEditDialog"
        width="50%" @close="editFormDialogClear" >
        <!-- 内容区 -->
        <el-form ref="editFormRef" :model="editForm" label-width="70px" :rules="eidtFormRules" >
           <el-form-item label="用户名" >
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
           <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱"  prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowEditDialog = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo" >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="isShowRoleDialog"
        width="50%">
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <P>分配新角色
              <el-select v-model="selectedRole" placeholder="请选择">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
        </P>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="distributeRole()">确 定</el-button>
        </span>
      </el-dialog>
      
  </div>
</template>

<script>
export default {
     data() {
         //邮箱验证规则
        let checkEmail = (rule,value,callback)=>{
           const regEmail = /^([a-zA-z0-9_-])+@([a-zA-z0-9_-])+\.([a-zA-z0-9_-])+/
           if(regEmail.test(value)){
               return callback()
           }
           return callback(new Error('请输入合法的邮箱'))
        }
        //手机号验证规则
        let checkMobile = (rule,value,callback)=>{
           const regMobile = /^([0-9])+/;
           if(regMobile.test(value)){
              return callback()
           }
           return callback(new Error('请输入合法的电话号码'));
           
        }
         return {
             queryInfo:{
              query:'',
              pagenum:1,
              pagesize:4
             },
            userList:[],
            total:0,
            //当前选中的用户信息
            userInfo:{},
            //获取的角色列表
            roleList:[],
            //当前选中角色的ID
            selectedRole:'',
            //控制添加用户时的对话框的显示
            isShowDialog:false,
            //控制修改用户信息对话框的显示
            isShowEditDialog:false,
            //控制角色分配对话框显示
            isShowRoleDialog:false,
            //要添加用户的表单数据
            addUserForm:{
                   username:'',
                   password:'',
                   email:'',
                   mobile:''
            },
            //修改用户对话框的表单数据
            editForm:{},
            //添加表单验证的规则对象
            addFormRules:{
                username:[
                  {required:true,message:'请输入用户名',trigger:'blur'},
                  {min:3,
                   max:10,
                   message:'用户的长度在3~10之间',
                   trigger:'blur'}
                  ],
                  password:[{required:true,message:'请输入密码',trigger:'blur'},
                  {min:6,
                   max:15,
                   message:'密码的长度在6~15之间',
                   trigger:'blur'
                   }],
                   email:[{required:true,message:'请输入邮箱',trigger:'blur'},
                   {validator:checkEmail,trigger:'blur'}
                  ],
                  mobile:[{required:true,message:'请输入电话号码',trigger:'blur'},
                   {validator:checkMobile,trigger:'blur'}]
            },
            eidtFormRules:{
                  email:[{required:true,message:'请输入邮箱',trigger:'blur'},
                   {validator:checkEmail,trigger:'blur'}
                  ],
                  mobile:[{required:true,message:'请输入电话号码',trigger:'blur'},
                   {validator:checkMobile,trigger:'blur'}],

            }
            
         }
     },
     created(){
         this.getUserList();
     },
     methods:{
         //获取用户信息
         async getUserList(){
            const {data:res} = await this.$http.get('users',{ params:this.queryInfo })
            if( res.meta.status !== 200) return this.$message.error('获取用户列表失败');
            this.userList = res.data.users;
            this.total = res.data.total;
            console.log(res);
         },
         //监听pagesize改变的回调
         handleSizeChange(newPageSize){
            console.log(newPageSize);
            this.queryInfo.pagesize = newPageSize;
            this.getUserList();
         },
         //监听页码改变的回调
         handleCurrentChange(newPage){
            console.log(newPage);
            this.queryInfo.pagenum = newPage;
            this.getUserList();

         },
         //当用户状态发生改变时的回调
         async userStateChange(userInfo){
            console.log(userInfo);
            const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
            if(res.meta.status !== 200) return this.$http.message.error('更新用户状态失败');
            this.$message.success('更新用户状态成功');
            
         },
         //当提交表单对话框关闭时的回调
         addUserFormClear(){
           this.$refs.addFormRef.resetFields();
         },
         //当修改用户表单对话框关闭时的回调
         editFormDialogClear(){
           this.$refs.editFormRef.resetFields();
         },
         //提交用户表单
         submit(){
            this.$refs.addFormRef.validate(async valid=>{
              if(!valid) return;
              //发起请求
              const {data:res} = await this.$http.post('users',this.addUserForm);
              if(res.meta.status !== 201 ) return this.$message.error('添加用户失败');
              this.$message.success('添加用户成功');
              this.getUserList();
              this.isShowDialog = false;
            })
         },
        //  
        async showEditDialog(id){
        
          const {data:res} = await this.$http.get(`users/${id}`);
          if(res.meta.status !== 200) return this.$message.error('获取失败');
          console.log(res);
          this.editForm = res.data;
            this.isShowEditDialog = true;
        },
        //提交修改用户信息的表单
        editUserInfo(){
            this.$refs.editFormRef.validate(async valid=>{
              if(!valid) return;
              //发起请求
              const {data:res} = await this.$http.put(`users/${this.editForm.id}`,{email:this.editForm.email,mobile:this.editForm.mobile});
              if(res.meta.status !== 200 ) return this.$message.error('修改失败');
              this.$message.success('用户信息编辑成功');

               this.isShowEditDialog = false;

               this.getUserList();
            })
        },
        //删除选中的用户信息
        removeUserInfo(id){
              this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                showCancelButton:true,
                showConfirmButton:true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(async() => {
               
                const {data:res} = await this.$http.delete(`users/${id}`);
                if(res.meta.status != 200 ) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.getUserList();
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });

         },
         //控制分配角色对话框显示
         async showRolesDialog(role){

           //获取角色列表
           const{data:res} = await this.$http.get('roles');
           if(res.meta.status !== 200 ) return this.$message.error('获取角色失败')
           this.roleList = res.data;

           //显示对话框
            this.isShowRoleDialog = true;
            this.userInfo = role;
         },
         //点击分配角色
         async distributeRole(){
            if(!this.userInfo) return this.isShowRoleDialog = false;
             const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRole});
             if(res.meta.status !== 200 ) return this.$message.error('分配失败');
              this.$message.success('分配成功');
              this.isShowRoleDialog = false;
              this.getUserList();
         }
         

   
     },
}
</script>

<style lang="less" scoped>

</style>